<?php
include "tools/tools.php";

function getcode_by_id($id){
    global $remote_ip;
    $db = remote_db();
    $sql = "SELECT * FROM `wp_zrz_invitation` WHERE id='$id'";
    $result = $db->query($sql);
    $code_info=array();
    if($result->num_rows > 0){
        $row = $result->fetch_assoc();
        $code_info['id'] = $row['id']; 
        $code_info['code'] = $row['invitation_nub']; 
        $code_info['status'] = $row['invitation_status']; 
    }
    return $code_info;
}
function getcode_by_code($code){
    global $remote_ip;
    $db = remote_db();
    $sql = "SELECT * FROM `wp_zrz_invitation` WHERE invitation_nub='$code'";
    $result = $db->query($sql);
    $code_info=array();
    if($result->num_rows > 0){
        $row = $result->fetch_assoc();
        $code_info['id'] = $row['id']; 
        $code_info['code'] = $row['invitation_nub']; 
        $code_info['status'] = $row['invitation_status']; 
    }
    return $code_info;
}

function delete_by_id($id){
    global $remote_ip;
    $db = remote_db();
    $sql = "DELETE FROM `wp_zrz_invitation` WHERE `wp_zrz_invitation`.`id` = $id";
    $result = $db->query($sql);
    return $result;
}

function generate($credit){
    global $remote_ip;
    $code = create_guid();

    $db = remote_db();
    $sql = "INSERT INTO `wp_zrz_invitation` (`invitation_nub`,`invitation_owner`,`invitation_credit`) VALUES ('$code','10','$credit')";
    $result = $db->query($sql);
    if ($result){
        return getcode_by_code($code);
    }
    else return false;
}

function create_guid($inv = true){

    $guid = '';
    $uid = uniqid ( "", true );

    $data = 'invite';
    $data .= $_SERVER ['REQUEST_TIME'];     // 请求那一刻的时间戳
    $data .= $_SERVER ['HTTP_USER_AGENT'];  // 获取访问者在用什么操作系统
    $data .= $_SERVER ['SERVER_ADDR'];      // 服务器IP
    $data .= $_SERVER ['SERVER_PORT'];      // 端口号
    $data .= $_SERVER ['REMOTE_ADDR'];      // 远程IP
    $data .= $_SERVER ['REMOTE_PORT'];      // 端口信息

    $hash = strtoupper ( hash ( 'ripemd128', $uid . $guid . md5 ( $data ) ) );

    if($inv){
        $guid = substr ( $hash, 0, 4 ). substr ( $hash, 8, 4 ). substr ( $hash, 12, 4 ). substr ( $hash, 16, 4 ).substr ( $hash, 20, 4 );
    }else{
        $guid = substr ( $hash, 0, 4 ) . '-' . substr ( $hash, 8, 4 ) . '-' . substr ( $hash, 12, 4 ) . '-' . substr ( $hash, 16, 4 ) . '-' . substr ( $hash, 20, 4 );
    }
    
    return $guid;
}